home *** CD-ROM | disk | FTP | other *** search
- Path: hubcap.clemson.edu!hubcap!mjs
- From: mjs@hubcap.clemson.edu (M. J. Saltzman)
- Newsgroups: comp.lang.c
- Subject: Re: is getopt() ANSI and portable ?
- Date: 22 Mar 96 01:50:05 GMT
- Organization: Clemson University
- Message-ID: <mjs.827459405@hubcap>
- References: <31512EC7.389F@eso.org>
- NNTP-Posting-Host: hubcap.clemson.edu
- X-Newsreader: NN version 6.5.0 #1
-
- Nicolas Devillard <nDevil@eso.org> writes:
-
- >I do not want to reinvent the wheel by creating again my own
- >command line parser. I found this getopt() function being part
- >of stdlib, but I'd like to know:
-
- >1. If it is part of the ANSI C stdlib ?
-
- No, it's not.
-
- >2. If it is a portable call ? I cannot find it in the POSIX prog guide.
-
- Mark Horton's 1990 _Portable C Programming_ book rates it as only
- moderately portable. It's a System III and System V Unix function,
- but is not common elsewhere.
-
- Attached is a public-domain version from AT&T (as published in Appendix F
- of Horton). No warranty, express or implied, etc., etc., etc.
-
- Matthew Saltzman
- Clemson University Math Sciences
- mjs@clemson.edu
-
- -------------------------getopt.c-----------------------------
- /*LINTLIBRARY*/
- #define NULL 0
- #define EOF (-1)
- #define ERR(s, c) if(opterr) {\
- extern int strlen(), _write();\
- char errbuf[2];\
- errbuf[0] = c; errbuf[1] = '\n';\
- (void) _write(2, argv[0], (unsigned)strlen(argv[0]));\
- (void) _write(2, s, (unsigned)strlen(s));\
- (void) _write(2, errbuf, 2);}
-
- extern int strcmp();
- extern char *strchr();
- /*
- * If building the regular library, pick up the definitions
- * from this file. If building the shared library, pick up
- * definitions from opt_data.c
- */
-
- extern int opterr, optind, optopt;
- extern char *optarg;
-
- static char error1[] = ": option requires an argument -- ";
- static char error2[] = ": illegal option -- ";
-
- int
- getopt(argc, argv, opts)
- int argc;
- char **argv, *opts;
- {
- static int sp = 1;
- register char c;
- register char *cp;
-
- if(sp == 1)
- if(optind >= argc ||
- argv[optind][0] != '-' || argv[optind][1] == '\0')
- return(EOF);
- else if(strcmp(argv[optind], "--") == NULL) {
- optind++;
- return(EOF);
- }
- optopt = c = (unsigned char)argv[optind][sp];
- if(c == ':' || (cp=strchr(opts, c)) == NULL) {
- ERR(error2,c);
- if(argv[optind][++sp] == '\0') {
- optind++;
- sp = 1;
- }
- return('?');
- }
- if(*++cp == ':') {
- if(argv[optind][sp+1] != '\0')
- optarg = &argv[optind++][sp+1];
- else if(++optind >= argc) {
- ERR(error1,c);
- sp = 1;
- return('?');
- } else
- optarg = argv[optind++];
- sp = 1;
- } else {
- if(argv[optind][++sp] == '\0') {
- sp = 1;
- optind++;
- }
- optarg = NULL;
- }
- return(c);
- }
- ------------------------------------------
- --
- Matthew Saltzman
- Clemson University Math Sciences
- mjs@clemson.edu
-